<template>
   <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
         <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
         <el-breadcrumb-item>用户管理</el-breadcrumb-item>
         <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
         <el-row :gutter="20">
         <el-col :span="16">
            <el-input v-model="queryInfo.query"  placeholder="请输入内容">
              <el-button @click="getUserlist" slot="append" icon="el-icon-search"></el-button>
            </el-input>
         </el-col>
         <el-col :span="4">
            <el-button @click="addDialog = true" type="primary">添加用户</el-button>
         </el-col>
         </el-row>
         <!-- 表格显示用户信息 -->
         <el-table border stripe :data="userlist" style="width:100%">
            <el-table-column type="index" label="#" />
            <el-table-column prop="username" label="姓名" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="mobile" label="电话" />
            <el-table-column prop="role_name" label="角色" />
            <el-table-column label="状态" >
               <template slot-scope="scope">
                  <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state" >
                  </el-switch>
               </template>
            </el-table-column>
            <el-table-column width="180px" label="操作" >
               <template slot-scope="scope">
               <el-button size="mini" type="primary" icon="el-icon-edit"></el-button>
               <el-button @click="deluser(scope.row)" size="mini" type="danger" icon="el-icon-delete"></el-button>
               <el-button @click="showRoleDialog(scope.row)" size="mini" type="warning" icon="el-icon-setting"></el-button>
               </template>
            </el-table-column>
         </el-table>
         <!-- 分页 -->
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[2, 5, 10, 50]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
         </el-pagination>
      </el-card>

      <!-- 新增对话框 -->
      <el-dialog
      title="新增用户"
      :visible.sync="addDialog"
      width="30%"
      :before-close="handleClose">
      <!-- 放个表单 -->
      <el-form :model="addForm" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="addDialog = false">取 消</el-button>
         <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
      </el-dialog>


      <!-- 分配角色对话框 -->
      <el-dialog
      title="分配角色"
      :visible.sync="roleDialog"
      width="30%"
      :before-close="handleClose">
      <!-- 放个表单 -->
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色
         <el-select v-model="roleId" placeholder="请选择">
            <el-option
               v-for="item in rolelist"
               :key="item.id"
               :label="item.roleName"
               :value="item.id">
            </el-option>
         </el-select>
        </p>
      </div>
      <!--  -->
      <span slot="footer" class="dialog-footer">
         <el-button @click="roleDialog = false">取 消</el-button>
         <el-button @click="setUserRole" type="primary">确 定</el-button>
      </span>
      </el-dialog>
   </div>
</template>

<script>
export default {
   data(){
      return {
         userlist: [],
         queryInfo : {
            query: '',
            pagenum: 1,
            pagesize: 5
         },
         total: 0 ,
         addDialog: false,
         roleDialog: false,
         //表单数据对象
         addForm:{
            username: '',
            password: '',
            email: '',
            mobile: ''
         },
         userInfo: {},
         roleId: '',
         rolelist: []
      }
   },
   created(){
     this.getUserlist();   //获取用户数据
   },
   methods:{
      async getUserlist(){
        let ret = await this.http.get('users', {params: this.queryInfo})
        console.log('刷新', ret );
        this.userlist = ret.data.users
        this.total = ret.data.total
      },
      // 页面大小改变
      handleSizeChange(size){
         console.log('页面大小改变',size);
         this.queryInfo.pagesize = size
         this.getUserlist()
      },
      // 当前页改变
      handleCurrentChange(p){
         console.log('当前页改变',p);
         this.queryInfo.pagenum = p
         this.getUserlist() 
      },
      // 用户状态改变
      async userStateChange(u){
         // console.log( u );
         let path =  `users/${u.id}/state/${u.mg_state}`
         let ret =await  this.http.put( path )
         console.log( ret );
         if(ret.meta.status != 200){
            u.mg_state = !u.mg_state 
            return this.$message.error(ret.meta.msg )
         }
         this.$message.success(ret.meta.msg )
      },
      //对话框关闭
      handleClose(){
         console.log('框关闭....');
         //this.$refs.addFormRef.resetFields()
      },
      //新增用户
      async adduser(){
         let ret = await this.http.post('users',this.addForm)           
         console.log( ret );
         if(ret.meta.status == 201){
            this.$refs.addFormRef.resetFields()
            this.$message.success(ret.meta.msg )
            this.addDialog = false  //消失
            this.getUserlist()  //刷新
            return;
         }
      },
      async deluser( u ){
        let ok =await this.$confirm('是否永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if( ok != 'confirm'){
           return ;
        }
         let ret = await this.http.delete('users/'+u.id)
         console.log( ret );
         if(ret.meta.status == 200){
            this.$message.success(ret.meta.msg )
            this.getUserlist() //刷新
            return;
         }     
      },
      // 显示分配对话框
      async showRoleDialog(u){
         this.roleDialog = true
         this.userInfo = u 
         // 查所有角色
         let ret = await this.http.get('roles')
         this.rolelist = ret.data 
         console.log( ret);
      },
      // 给用户分配角色 uid, rid
      async setUserRole(){
         let path = `users/${this.userInfo.id}/role`
         let ret = await this.http.put(path, {rid:this.roleId })
         console.log( ret );
         if(ret.meta.status == 200){
            this.roleDialog = false
            this.$message.success(ret.meta.msg )
            this.getUserlist() //刷新
            return;
         }  
      }
   }
}
</script>

<style>

</style>